<script setup lang="ts">
import Tab from './Tab.vue';
import { computed, onMounted, onUpdated, ref, useSlots } from 'vue';


const slots = useSlots()
const props = defineProps({
    selected:{
        type:String
    }
})
const emit = defineEmits(['update:selected'])

const defaults = slots.default()
defaults.forEach(tag => {
    if (tag.type !== Tab) {
        throw new Error("Tabs子标签必须是 Tab");
    }
})

const titles = defaults.map(tag => tag.props?.title)
const current = computed(() => {
    return defaults.find(tag => tag.props?.title === props.selected)
})

const select = (title:string) => {
    emit('update:selected',title)
}

const navItems = ref<HTMLDivElement[]>([])
const indicator = ref<HTMLDivElement>(null)
const container = ref<HTMLDivElement>(null)
const switchLine = ()=> {
    const result = navItems.value.find(div => div.classList.contains('selected')) as HTMLDivElement
    const {width} = result?.getBoundingClientRect()
    indicator.value.style.width = width + 'px'
    const {left:left1} = container.value.getBoundingClientRect()
    const {left:left2} = result.getBoundingClientRect()
    const left = left2 - left1
    indicator.value.style.left = left + 'px' 
}
onMounted(switchLine)
onUpdated(switchLine)
</script>
<template>
    <div class="wui-tabs">
        <div class="wui-tabs-nav" ref="container">
            <div class="wui-tabs-nav-item" 
            :class="{selected:t === selected}"
            @click="select(t)"
            v-for="(t, index) in titles"
            ref="navItems">{{ t }}</div>
            <div class="wui-tabs-nav-indicator" ref="indicator"></div>
        </div>
        <div class="wui-tabs-content">
            <component :is="current" :key="current?.props?.title"/>
        </div>
    </div>
</template>

<style lang="scss">
$blue:rgb(25, 137, 250);
$color:#333;
$border-color:#d9d9d9;

.wui-tabs {
    &-nav {
        display: flex;
        color: $color;
        border-bottom: 1px solid $border-color;
        position: relative;
        &-item {
            padding: 8px 0;
            margin: 0 16px;
            cursor: pointer;

            &:first-child {
                margin-left: 0;
            }

            &.selected {
                color: $blue;
            }
        }

        &-indicator{
            position: absolute;
            height: 3px;
            background: $blue;
            left: 0;
            bottom: -1px;
            width: 100px;
            transition: all 0.2s ;
        }
    }

    &-content{
        padding: 8px 0;
    }
}
</style>